#include <stdio.h> // fget要用的
#include <stdlib.h>
#include <string.h>
#include <curl/curl.h>
#include "cJSON.h"

/*
构造JSON请求报文
{
    "perception": {
        "inputText": {
            "text": "你好"
        },
    },
    "userInfo": {
        "apiKey": "abffa9d2e6d94ceaa26424b2eb5f62c9",
        "userId": "dyp"
    }
}
*/
char* robot_make_reqeire(const char* apikey, const char* text)
{

    //判断输入字符串长度不为零
    if (strlen(text) ==0)
    {
        return NULL;
    }
    cJSON* request = cJSON_CreateObject();
    cJSON* userInfo = cJSON_CreateObject();

    cJSON *perception = cJSON_CreateObject();
    cJSON *inputText =  cJSON_CreateObject();

    //userInfo
    cJSON_AddStringToObject(userInfo, "apiKey", apikey);
    cJSON_AddStringToObject(userInfo, "userId", "dyp");
    cJSON_AddItemToObject(request, "userInfo", userInfo);

    //将perceptionJSON字符数据结构转换为字符串
    cJSON_AddStringToObject(inputText, "text", text);
    cJSON_AddItemToObject(perception, "inputText", inputText);

    cJSON_AddItemToObject(request,"perception", perception);

    //将JSON数据结构转换为字符串
    return cJSON_Print(request);
}

//发送请求报文，有两个作用，发送和接受响应
char* robot_send_request(const char* request)
{
    CURL* curl = curl_easy_init();

    FILE* fp;

    //以只写方式打开文件
    //fp = fopen("hello.txt", "w");

    //响应消息的地址
    char* response = NULL;
    //响应消息的长度
    size_t resplen = 0;
    //创建内存文件，当通过文件句柄写入数据时，会自动分配内存ps：&是取地址
    fp = open_memstream(&response, &resplen);

    //配置接口
    curl_easy_setopt(curl, CURLOPT_URL, "http://openapi.tuling123.com/openapi/api/v2");
    //配置客户端，使用HTTP的POST方法发送请求消息
    curl_easy_setopt(curl, CURLOPT_POST, 1);
    //配置通过POST发送的数据
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, request);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);

    //发送HTTP请求消息，等待服务器的响应消息
    CURLcode error = curl_easy_perform(curl);
    if (error != CURLE_OK)
    {
        fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(error));
        curl_easy_cleanup(curl);
        fclose(fp);
        return NULL;
    }


    //释放
    curl_easy_cleanup(curl);

    //关闭机器人发回的报文
    fclose(fp);

    return (response);

    free(response);
}


/*
{
  "emotion": {
    "robotEmotion": {
      "a": 0,
      "d": 0,
      "emotionId": 0,
      "p": 0
    },
    "userEmotion": {
      "a": 0,
      "d": 0,
      "emotionId": 10300,
      "p": 0
    }
  },
  "intent": {
    "actionName": "",
    "code": 10004,
    "intentName": ""
  },
  "results": [
    {
      "groupType": 1,
      "resultType": "text",
      "values": {
        "text": "你好呀～找我干嘛？"
      }
    }
  ]
}
解析json报文

*/
char* robot_trans_response(char* response)
{
    cJSON* json = cJSON_Parse(response);
    if (json == NULL)
    {
        const char* error_pos = cJSON_GetErrorPtr();
        if (error_pos != NULL)
        {
            fprintf(stderr, "Error before: %s\n", error_pos);
        }
        return NULL;
    }

    cJSON* results = cJSON_GetObjectItemCaseSensitive(json, "results");
    //printf("results: %s\n", cJSON_Print(results));

    cJSON* list = cJSON_GetArrayItem(results, 0);

    cJSON* values = cJSON_GetObjectItemCaseSensitive(list, "values");
    
    cJSON* text = cJSON_GetObjectItemCaseSensitive(values, "text");

    //释放json
    cJSON_free(json);
    free(response);
    return text -> valuestring;

}

//百度语言合成API，一次最多可转换2048个字符
#define LINE_LEN 128

//保存输入字符串的缓存区
char line[LINE_LEN];

int main()
{
    char *apikey = "abffa9d2e6d94ceaa26424b2eb5f62c9";
     while (fgets(line, LINE_LEN, stdin) != NULL)
    {
        //构造请求报文
        char* request = robot_make_reqeire(apikey, line);
        if(request ==NULL)
        {
            continue;
        }

        //将请求报文发送给图灵机器人
        char* response_1 = robot_send_request(request);

        //打印接受到的报文
        printf("接受到的报文 : %s\n", response_1);

        //打印解析出来的字符串
        char* answer = robot_trans_response(response_1);
        printf("解析出来的字符串是: %s \n", answer);


    }

} 